package com.wordsay.analyer.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.lionsoul.jcseg.core.IWord;

import com.wordsay.analyer.Analyer;
import com.wordsay.comparator.CountComparator;
import com.wordsay.context.Context;
import com.wordsay.entity.GDialogAnalystResult;
import com.wordsay.entity.GroupDialog;
import com.wordsay.entity.HotItem;
import com.wordsay.entity.PDialogAnalystResult;
import com.wordsay.entity.PersonDialog;
import com.wordsay.entity.Talk;
import com.wordsay.util.DateTimeUtil;

/**
 * 个性分析器
 * @author squirrelrao
 *
 */
public class GroupAnalyer implements Analyer {

	@Override
	public Object execute(Object target) throws Exception {

		if(!(target instanceof GroupDialog)){
			System.out.println("--->found error dialog type,should be GroupDialog, but it's "+target.getClass().getName());
			return null;
		}
		GroupDialog dialog = (GroupDialog)target;
		
		GDialogAnalystResult result = new GDialogAnalystResult();
		
		//analyst the talks
		this.baisicAnalystTalks(result, dialog.getTalks());
				
		return result;
	}
	
	/**
	 * analyst the talks
	 * @param result
	 * @param talks
	 */
	private void baisicAnalystTalks(GDialogAnalystResult result,List<Talk> talks){
		
		if(talks == null || talks.size() == 0) {
			
			return;
		}
		
		long totalWordCount = 0;
		long totalTalkCount = 0;
		
		List<HotItem> wordsList = new ArrayList<HotItem>();
		List<HotItem> periodsList = new ArrayList<HotItem>();

		int indexOf = -1;
		for(Talk talk : talks){
			
			List<IWord> words = talk.getIwords();
			
			for(IWord word : words){
				
				String value = word.getValue().trim().equals("图片") ? "[飞信表情]" : word.getValue();

				HotItem item = new HotItem(value,1);
				indexOf = -1;
				if((indexOf = wordsList.indexOf(item)) != -1){
					
					wordsList.get(indexOf).frequencyAdd();
				
				}else if(!"".equals(word.getValue().trim())){
				    wordsList.add(item);	
				}
				totalWordCount++;


			}
			
			indexOf= -1;
			HotItem periodItem = new HotItem(DateTimeUtil.getHour(talk.getTime()),1);
			if((indexOf = periodsList.indexOf(periodItem)) != -1){
				
				periodsList.get(indexOf).frequencyAdd();
				
			}else{
				periodsList.add(periodItem);
			}
			
			totalTalkCount++;
		}
		
	    int similarWordsBaseCount =  Integer.valueOf(Context.getInstance().getContextMap().get("similarWordsBaseCount"));

		Collections.sort(wordsList, new CountComparator());
		int subLength = wordsList.size() > similarWordsBaseCount ? similarWordsBaseCount : wordsList.size();
		result.setHotWords(wordsList.subList(0, subLength));
		Collections.sort(periodsList,new CountComparator());
		subLength = periodsList.size() > 3 ? 3 : periodsList.size();
		result.setHotPeriods(periodsList.subList(0, subLength));
		result.setWordsCount(totalWordCount);
		result.setTalkCount(totalTalkCount);
	}

}
